import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UploadFile, NzNotificationService } from 'ng-zorro-antd';
import { HttpService } from '../../../services/http.service';
import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http';
import { filter } from 'rxjs/operators';
import { applicationForm, imageurl, direction } from '../../../urlConfig';
import { Router } from '@angular/router';
@Component({
  selector: 'app-add-we',
  templateUrl: './add-we.component.html',
  styleUrls: ['./add-we.component.styl']
})
export class AddWeComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private http: HttpService, private http1: HttpClient,
    private notification: NzNotificationService,
    private router: Router,
  ) { }
  validateForm: FormGroup;
  fileList = [];
  uploading = false;
  // showUploadList = {
  //   showPreviewIcon: true,
  //   showRemoveIcon: true,
  //   hidePreviewIconInNonImage: true
  // };

  // previewImage: string | undefined = '';
  previewVisible = false;
  language: number; // 存放方向的key值
  nodes = [];

  ngOnInit(): void {

    this.validateForm = this.fb.group({
      name: [null, [Validators.required, Validators.pattern(/^[\u4e00-\u9fa5]{2,8}$/)]],
      // phoneNumberPrefix: ['+86'],
      phoneNumber: [null, [Validators.required, Validators.pattern(/^1[34578]\d{9}$/)]],
      email: [null, [Validators.email, Validators.required]],
      sex: ['0', [Validators.required]],
      username: [null, [Validators.required, Validators.pattern(/^[0-9]{10}$/)]],        // 学号
      grade: [null, [Validators.required, Validators.pattern(/^\d{2}[\u4e00-\u9fa5]{2}\d{1}班{1}$|^\d{2}[\u4e00-\u9fa5]{2}卓越班$/)]],// 班级
      directionId: [null, [Validators.required]],                                       // 方向 （前 后 ）
      // languageType: ['', [Validators.required]],
      qq: ['', []],
      weChat: [null, [Validators.required, Validators.pattern(/^[a-zA-Z][a-zA-Z0-9_-]{5,19}$|^1[34578]\d{9}$/)]],
      comment: [null, [Validators.required, Validators.minLength(10)]],                // 自我介绍
    });

    this.http.getData(direction).subscribe((response: any) => {
      if (response.code === 200) {
        this.nodes = response.data;
        // console.log(response.data);

      }
    })
  }

  ngAfterContentChecked(): void {
    //Called after every check of the component's or directive's content.
    //Add 'implements AfterContentChecked' to the class.
    var element: any = document.documentElement.querySelectorAll(".ant-tree li .ant-tree-node-content-wrapper");
    for (var i = 0; i < element.length; i++) {
      element[i].style.width = "100%"
    }
  }

  submitForm() {

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (
      this.myvalidateForm('name')
      && this.myvalidateForm('phoneNumber')
      && this.myvalidateForm('email')
      && this.myvalidateForm('username')
      && this.myvalidateForm('grade')
      && this.myvalidateForm('directionId')
      && this.myvalidateForm('weChat')
      && this.myvalidateForm('comment')
    ) {
      if (this.fileList.length === 0) {
        this.createNotification('error')
      } else {
        this.handleUpload();
      }
    }
  }

  // handlePreview = (file: UploadFile) => {
  //   this.previewImage = file.url || file.thumbUrl;
  //   this.previewVisible = true;
  // }


  beforeUpload = (file: UploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
  };

  handleUpload() {
    const formData = new FormData();
    this.fileList.forEach((file: any) => {
      formData.append('files[]', file);
    });
    this.uploading = true;
    const req = new HttpRequest('POST', imageurl, formData, {
    });
    this.http1
      .request(req)
      .pipe(filter(e => e instanceof HttpResponse))
      .subscribe(
        (event: any) => {
          this.uploading = false;
          this.fileList = [];
          if (event.body.data.filename) {
            var form = this.validateForm.value;
            form.image = event.body.data.filename;
            // console.log(this.validateForm.value);
            this.validateForm.value.directionId = this.validateForm.value.directionId;
            this.http.postData(applicationForm, this.validateForm.value).subscribe((response: any) => {
              if (response.code === 201) {
                this.DuplicateSubmission('error');
              } else {
                this.router.navigate(['submitsuccess'])
              }

            })
          }
        },
        () => {
          this.uploading = false;
        }
      );
  }

  myvalidateForm(formControlName) {
    return this.validateForm.get(formControlName).errors === null;
  }

  createNotification(type: string): void {
    this.notification.create(
      type,
      '提交失败',
      '请上传照片!'
    );
  }

  DuplicateSubmission(type: string): void {
    this.notification.create(
      type,
      '提交失败',
      '您以提交申请,请耐心等待!'
    );
  }

}

